import axios from 'axios'
import Vue from 'vue'
import { Loading } from 'element-ui'
import store from '@/store'
import qs from 'qs'

// 不带全局loading的请求实例
export const requestWithoutLoading = createBaseInstance()
// 带全局loading的请求实例
// 传入函数是因为需要在处理请求结果handleResponse之前处理loading
// 所以要在内部插入loading拦截器的处理逻辑
export const request = createBaseInstance()

// 通用的axios实例
function createBaseInstance() {
  const instance = axios.create({
    // baseURL: '/api',
    withCredentials: true,
    crossDomain: true
  })

  instance.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    if (config.method === 'post') {
      config.data = qs.stringify({
        ...config.data
      })
    }
    return config;
  })

  instance.interceptors.response.use(response => {
    return response.data
  }, (err) => {
    Vue.prototype.$message.error("快滚！快滚！快滚！内部错误，你无法解决！")
    throw err
    // return new Promise(() => { })
  })
  return instance
}

mixinLoading(request.interceptors)

let loading
let loadingCount = 0
function mixinLoading(interceptors) {
  interceptors.request.use(loadingRequestInterceptor)
  interceptors.response.use(
    loadingResponseInterceptor,
    loadingResponseErrorInterceptor
  )

  function loadingRequestInterceptor(config) {
    if (!loading) {
      loading = Loading.service({
        target: 'body',
        background: 'transparent',
        text: '载入中',
      })
      store.commit('global/setAxiosLoading', true)
    }
    loadingCount++

    return config
  }

  function handleResponseLoading() {
    loadingCount--
    if (loadingCount === 0) {
      loading.close()
      loading = null
      store.commit('global/setAxiosLoading', false)
    }
  }

  function loadingResponseInterceptor(response) {
    handleResponseLoading()
    return response
  }

  function loadingResponseErrorInterceptor(e) {
    handleResponseLoading()
    throw e
  }
}

// 获取歌曲播放地址
export const getSongUrl = id => request.post(`/api/song/enhance/player/url?ids=[${id}]&br=128000`)

// 获取歌曲详情
export const getSongDetail = params => request.post('/api/v3/song/detail', params)

// 获取热词
export const getSearchHot = () => requestWithoutLoading.post('/api/search/hot?type=1111')

// 歌词
export const getLyric = id => request.post(`/api/song/lyric?id=${id}&lv=-1&kv=-1&tv=-1`)

// 专辑内容
export const getAlbum = id => request.post(`/api/v1/album?id=${id}`)

// 获取播放列表详情
export const getPlaylistDetail = params => request.post('/api/v3/playlist/detail', params)

// 获取轮播图数据
export const getBanner = params => request.post('/api/v2/banner/get', params)

// 获取推荐歌单
export const getPersonalizedPlaylist = params => request.post('/api/personalized/playlist', params)

// 获取最新歌曲
export const getPersonalizedNewsong = params => request.post('/api/personalized/newsong', params)

// 获取推荐MV
export const getPersonalizedMv = () => request.post('/api/personalized/mv')

// 获取歌曲播放地址
export const getMusicUrl = id => request.post(`/api/song/enhance/player/url?ids=[${id}]&br=128000`)

// 获取精品歌单
export const getTopPlaylist = param => request.post('/api/playlist/highquality/list', param)

// 获取歌单列表
export const getPalylist = param => request.post('/api/playlist/list', param)

// 获取最新音乐
export const getNewSongs = param => request.post('/api/v1/discovery/new/songs', param)

// 获取Mv列表
export const getMvs = param => request.post('/api/mv/all', param)

// 查询
export const search = param => request.post('/api/search/get', param)

// 获取歌单评论
export const getPlaylistComments = (id, param) => requestWithoutLoading.post(`/api/v1/resource/comments/A_PL_0_${id}`, param)

// 获取MV播放地址
export const getMvUrl = param => request.post(`/api/song/enhance/play/mv/url`, param)

// 获取MV详情
export const getMvDetail = param => request.post(`/api/mv/detail`, param)

// 获取歌手头像
export const getArtistIcon = (id, param) => requestWithoutLoading.post(`/api/v1/artist/${id}`, param)

// 获取MV评论
export const getMvComment = (id, param) => requestWithoutLoading.post(`/api/v1/resource/comments/R_MV_5_${id}`, param)

// 获取相关MV
export const getSimiMvUrl = param => request.post('/api/discovery/simiMV', param)

// 获取歌曲评论
export const getSongComment = (id, param) => requestWithoutLoading.post(`/api/v1/resource/comments/R_SO_4_${id}`, param)

// 相似音乐
export const getSimiSongs = id => requestWithoutLoading.get(`/api/v1/discovery/simiSong?songid=${id}&limit=5`)

// 获取相似歌单
export const getSimiPlaylists = id => requestWithoutLoading.get(`/api/discovery/simiPlaylist?songid=${id}&limit=3`)

export const getUserDetail = uid => requestWithoutLoading.get(`/api/v1/user/detail/${uid}`)

export const getUserPlaylist = uid => requestWithoutLoading.get("/api/user/playlist", { params: { uid, limit: 1000 } })

// rz每日推荐
export const getRzRecommendSongs = () => request.get('http://rzi2016.online/thirdapi/sakura')